import React from 'react';
import { Comment, Avatar, Form, Button, Input, message } from 'antd';
import moment from 'moment';
import CommentBox from '../CommitBox';
import http from '../../api/index';
import { HeartFilled, HeartOutlined } from '@ant-design/icons';
import { getLocalUserInfo } from '../../utils/global';
import { connect } from 'react-redux';
import { getCommentInfo } from '../../store/comment.redux';
import { setUserInfo } from '../../store/app.redux';


const { TextArea } = Input;


const Editor = ({ onChange, onSubmit, submitting, value, placeholder, editorRef }) => {
    return (
        <>
            <Form.Item>
                <TextArea
                    className={'editor'}
                    ref={editorRef}
                    rows={4}
                    onChange={onChange}
                    value={value}
                    placeholder={placeholder ? `@ ${placeholder}` : ''}
                />
            </Form.Item>
            <Form.Item>
                <Button htmlType="submit" loading={submitting} onClick={onSubmit} type="primary">
                    Add Comment
          </Button>
            </Form.Item>
        </>
    )
};
@connect(
    state => ({
        blogInfoData: state.blogInfo.blogInfoData,
        userInfoData: state.app.userInfoData,
        commentInfoData: state.comment.commentInfoData
    }),
    {
        getCommentInfo,
        setUserInfo
    }
)
class index extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            submitting: false,
            commentId: '',
            receiverNm: '',
            value: '',
            boxType: '', //comment or like
            isFocus: false
        };
        this.editorRef = React.createRef();
    }
   
    getUserInfo = () => {
        let userInfo = getLocalUserInfo();
        this.props.setUserInfo(userInfo); //redux获取用户数据
    }

    onRef = (ref) => {
        this.childCommitBox = ref
    }
    focusTextEditor = async () => {
        // 直接使用原生 API 使 text 输入框获得焦点
        // 注意：我们通过 "current" 来访问 DOM 节点
        console.log(this.editorRef)
        window.document.querySelector('.editor').focus();
    }

    changeSubmitting = () => {
        this.setState((state) => ({
            submitting: !state.submitting
        }));
    }
    // 处理提交
    handleSubmit = () => {
        if (!this.state.value) {
            message.warning('Please input your comment!');
            return;
        }
        this.openBox('comment');
    };
    // 获取评论数据
    getCommentData = async () => {
        await this.props.getCommentInfo(this.props.blogInfoData.blogId)
        await setTimeout(() => {
            this.setState({
                submitting: false,
                value: ''
            });
        }, 1000);
    }


    handleChange = e => {
        this.setState({
            value: e.target.value,
        });
    };

    openBox = async (type) => {
        // 盒子类型
        this.setState((state) => ({
            boxType: type
        }))
        await this.props.setUserInfo(getLocalUserInfo()); //redux插入用户数据
        if (this.props.userInfoData.userNm) {
            if (type === 'comment') {
                this.addCommentData();
                this.setState({
                    value: '',
                });
                this.getCommentData();
            }
            else if (type === 'like') {

            }
            this.changeSubmitting();
        } else {
            this.childCommitBox.showModal();//调用自组建方法
        }
    }
    addCommentData = () => {
        const data = {
            blogId: this.props.blogInfoData.blogId,
            commentId: this.state.commentId,
            userNm: this.props.userInfoData.userNm,
            receiverNm: this.state.receiverNm,
            commentContent: this.state.value,
            dataTime: new Date().getTime()
        }
        http.blog.addComment(data).then((res) => {

        })
    }

    changeLike = (blogId, isLike) => {
        // 盒子类型
        this.setState((state) => ({
            boxType: 'like'
        }))
    }
    changeReceiverNm = (commentId, receiverNm) => {
        this.setState((state) => ({
            commentId,
            receiverNm
        }))
        this.focusTextEditor();
    }

    render() {

        const CommentVNode = (props) => {
            if (!!props.data) {
                return <>
                    {props.data.map((item, index) => (
                        <Comment
                            key={index}
                            actions={[<span className={'reply-to'} onClick={() => this.changeReceiverNm(item.commentId, item.userNm)}>Reply to</span>]}
                            author={<>{item.userNm} <span style={{ color: '#1890ff' }}>@</span> {item.receiverNm}</>}
                            avatar={
                                <>
                                    <Avatar
                                        style={{ backgroundColor: item.avatarColor, verticalAlign: 'middle' }}
                                        size="large"
                                        gap={3}
                                    >{item.userNm}
                                    </Avatar>
                                </>
                            }
                            content={<>{item.content}</>}
                            datetime={<>{moment(item.dataTime).startOf('hour').fromNow()}</>}
                        >
                            <CommentVNode data={item.children} />
                        </Comment>
                    ))
                    }
                </>
            } else {
                return (<></>)
            }
        };

        
        const { submitting, value } = this.state;
        const { blogId, isLike, likeNum } = this.props.blogInfoData; //是否点赞 点赞数
        const { userNm, avatarColor } = this.props.userInfoData; //用户名 称头像
        return (
            <>
                {/* 点赞 */}
                <div style={{ textAlign: "center" }}>
                    <Button type={isLike ? 'primary' : ''} danger onClick={() => this.changeLike(blogId, isLike)}>
                        Like it {isLike ? likeNum : likeNum - 1}
                        {this.state.isLike ? <HeartFilled /> : <HeartOutlined />}
                    </Button>
                </div>
                {/* 评论 */}
                <CommentVNode data={this.props.commentInfoData} />
                <Comment
                    avatar={
                        (
                            <>
                                <Avatar
                                    style={{ backgroundColor: avatarColor ? avatarColor : '#1890ff', verticalAlign: 'middle' }}
                                    size="large"
                                    gap={3}
                                >{userNm ? userNm : 'visitor'}
                                </Avatar>
                            </>
                        )
                    }
                    content={
                        <Editor
                            onChange={this.handleChange}
                            onSubmit={this.handleSubmit}
                            submitting={submitting}
                            value={value}
                            placeholder={this.state.receiverNm}
                            editorRef={this.editorRef}
                        />
                    }
                />
                <CommentBox boxType={this.state.boxType} onRef={this.onRef} getUserInfo={this.getUserInfo} getCommentData={this.getCommentData} />

            </>
        );
    }
}


export default index;